﻿using UnityEngine;
using System.Collections;

public class CharacterPreviewManager : MonoBehaviour
{
    public UISprite[] traitIconImage;
    public UILabel[] traitNameLabel;
    public UILabel[] traitCategoryNameLabel;
    public UILabel[] traitBodyLabel;
    public UILabel[] drawCostLabel;

    public static DStoreCharacter charInfo;

    [HideInInspector]
    public GameObject m_3DModelObject;
    [HideInInspector]
    public Animation m_3DModelAnimation;
    public Transform m_3DModelPositionRoot;
    [HideInInspector]
    public Transform m_3DmodelPrevParent;
    public Animation characterMoveAnimation;

    public Transform[] animationButtons;
    public GameObject zoomInButton;
    public GameObject zoomOutButton;

    static CharacterPreviewManager _instance;
    public static CharacterPreviewManager instance
    {
        get { return _instance; }
    }

    void Awake()
    {
        if(_instance == null)
            _instance = this;
    }
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void OnEnable()
    {
        m_3DModelObject = CharacterDrawViewManager.instance.m_3DModelObjectList[CharacterDrawViewManager.instance.selectedItemIndex];
        m_3DModelAnimation = m_3DModelObject.GetComponent<Animation>();
        m_3DmodelPrevParent = m_3DModelObject.transform.parent;
        string modelName = GameData.Inst.ModelDefineDic[charInfo.modelNo];
        for (int i = 0; i < m_3DModelPositionRoot.childCount; i++)
        {
            Transform trans = m_3DModelPositionRoot.GetChild(i);
            if (modelName.Contains(trans.gameObject.name))
            {
                m_3DModelObject.transform.parent = trans;
                m_3DModelObject.transform.localPosition = Vector3.zero;
                m_3DModelObject.transform.localRotation = Quaternion.Euler(Vector3.zero);
                m_3DModelObject.transform.localScale = Vector3.one;
            }
        }
        SetCharacterInfos();
        SetAnimationButtons(0);
    }

    void OnDisable()
    {
        Debug.LogError("CharacterPreviewManager OnDisable()");
        m_3DModelObject.transform.parent = m_3DmodelPrevParent;
        m_3DModelObject.transform.localPosition = Vector3.zero;
        m_3DModelObject.transform.localRotation = Quaternion.Euler(Vector3.zero);
        m_3DModelObject.transform.localScale = Vector3.one;
        Animation ani = m_3DModelObject.GetComponent<Animation>();
        ani["lobby01"].clip.wrapMode = WrapMode.Loop;
        ani.Play("lobby01");
        CharacterDrawViewManager.instance.charUnitListViewObject.SetActive(true);
        CharacterDrawViewManager.instance.gameObject.SetActive(true);
        CharacterDrawViewManager.instance.tipShugoObject.SetActive(true);
    }

    public void SetCharacterInfos()
    {
        traitIconImage[0].spriteName = charInfo.trait1Value.ToString();
        traitIconImage[1].spriteName = charInfo.trait2Value.ToString();
        traitIconImage[2].spriteName = charInfo.trait3Value.ToString();
        traitNameLabel[0].text = TextController.GetStringWithId(string.Format("trait{0}", charInfo.trait1Value));
        float nameLabelWidth = traitNameLabel[0].width;
        string keyValue = null;
        if (charInfo.trait1Value / 100 > 0)
            keyValue = "uiCommonTextFeature";
        else if (charInfo.trait1Value < 11)
            keyValue = "uiCommonTextRace";
        else
            keyValue = "uiCommonTextClass";
        traitCategoryNameLabel[0].text = TextController.GetStringWithId(keyValue);
        Vector3 trans = traitCategoryNameLabel[0].transform.localPosition;
        trans.x = traitNameLabel[0].transform.localPosition.x + nameLabelWidth + 40f;
        traitCategoryNameLabel[0].transform.localPosition = trans;
        traitNameLabel[1].text = TextController.GetStringWithId(string.Format("trait{0}", charInfo.trait2Value));
        nameLabelWidth = traitNameLabel[1].width;
        if (charInfo.trait2Value / 100 > 0)
            keyValue = "uiCommonTextFeature";
        else if (charInfo.trait2Value < 11)
            keyValue = "uiCommonTextRace";
        else
            keyValue = "uiCommonTextClass";
        traitCategoryNameLabel[1].text = TextController.GetStringWithId(keyValue);
        trans = traitCategoryNameLabel[1].transform.localPosition;
        trans.x = traitNameLabel[1].transform.localPosition.x + nameLabelWidth + 40f;
        traitCategoryNameLabel[1].transform.localPosition = trans;
        traitNameLabel[2].text = TextController.GetStringWithId(string.Format("trait{0}", charInfo.trait3Value));
        nameLabelWidth = traitNameLabel[2].width;
        if (charInfo.trait3Value / 100 > 0)
            keyValue = "uiCommonTextFeature";
        else if (charInfo.trait3Value < 11)
            keyValue = "uiCommonTextRace";
        else
            keyValue = "uiCommonTextClass";
        traitCategoryNameLabel[2].text = TextController.GetStringWithId(keyValue);
        trans = traitCategoryNameLabel[2].transform.localPosition;
        trans.x = traitNameLabel[2].transform.localPosition.x + nameLabelWidth + 40f;
        traitCategoryNameLabel[2].transform.localPosition = trans;
        traitBodyLabel[0].text = TextController.GetStringWithId(string.Format("traitText{0}", charInfo.trait1Value));
        traitBodyLabel[1].text = TextController.GetStringWithId(string.Format("traitText{0}", charInfo.trait2Value));
        traitBodyLabel[2].text = TextController.GetStringWithId(string.Format("traitText{0}", charInfo.trait3Value));

        foreach(UILabel label in drawCostLabel)
            label.text = GameData.Inst.GetStoreGoodInfo(charInfo.charID).price.ToString();
    }

    void SetAnimation(int index)
    {
        switch (index)
        {
            case 0:
                m_3DModelAnimation.CrossFade("idle01", 0.5f);
                break;
            case 1:
                m_3DModelAnimation.CrossFade("attack01", 0.5f);
                m_3DModelAnimation.CrossFadeQueued("idle01", 0.5f);
                break;
            case 2:
                m_3DModelAnimation.CrossFade("skill01");
                m_3DModelAnimation.CrossFadeQueued("idle01", 0.5f);
                break;
            case 3:
                m_3DModelAnimation.CrossFade("victory01");
                m_3DModelAnimation.CrossFadeQueued("idle01", 0.5f);
                break;
        }
    }

    void SetAnimationButtons(int index)
    {
        for (int i = 0; i < m_ButtonLegth; i++)
        {
            if (i == index)
            {
                animationButtons[i].Find("on").gameObject.SetActive(true);
                animationButtons[i].Find("off").gameObject.SetActive(false);
            }
            else
            {
                animationButtons[i].Find("on").gameObject.SetActive(false);
                animationButtons[i].Find("off").gameObject.SetActive(true);
            }
        }

        SetAnimation(index);
    }

    int m_ButtonLegth = 4;
    public void OnClickedBattleReadyButton()
    {
        SetAnimationButtons(0);
    }

    public void OnClickedNormalAttackButton()
    {
        SetAnimationButtons(1);
    }

    public void OnClickedSkillAttackButton()
    {
        SetAnimationButtons(2);
    }

    public void OnClickedBattleVictoryButton()
    {
        SetAnimationButtons(3);
    }

    public void OnClickedZoomInButton()
    {
        characterMoveAnimation.CrossFade("Store_char_View_expansion", 0.5f);
        zoomInButton.SetActive(false);
        zoomOutButton.SetActive(true);     
    }

    public void OnClickedZoomOutButton()
    {
        characterMoveAnimation.CrossFade("Store_char_View_reduction", 0.5f);
        zoomInButton.SetActive(true);
        zoomOutButton.SetActive(false);     
    }

    public void OnClickedCharcterDrawButton()
    {
       BuyCharDrawItem(CharacterDrawViewManager.instance.selectedItemIndex);
    }

    public void BuyCharDrawItem(int charListIndex)
    {
        DStore storeGoodInfo = GameData.Inst.GetStoreGoodInfo(charInfo.charID);
        if (UserData.Instance.userModel.winPoint >= storeGoodInfo.price)
        {
            Popup_TwoButton popup = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
            popup.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiPopupStoreBuy").Replace("{0}", TextController.GetStringWithId(string.Format("charName{0}", charInfo.nameID))));
            popup.SetPopupWithYesNoString(TextController.GetStringWithId("uiCommonTextYes"), TextController.GetStringWithId("uiCommonTextNo"));
            popup.SetEventOK(gameObject, "OnClickedOkButtonAskBuyPopup");
        }
        else
        {
            Popup_OneButton popup = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            popup.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiPopupStoreLack1"));
        }
    }

    public void OnClickedOkButtonAskBuyPopup()
    {
        NetworkManager.Instance.C2S_BUY_STORE_ITEM(ResponseBuyCharDrawItem, charInfo.charID);
    }

    private void ResponseBuyCharDrawItem(ResponseModel<BuyStoreItemResultModel> result)
    {
        Debug.LogError(result);
        transform.parent.gameObject.GetComponent<Animation>().Play("RootAlpha_Out"); { }

        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }

        UserData.Instance.userModel.winPoint -= (short)GameData.Inst.GetStoreGoodInfo(charInfo.charID).price;

        CharacterDrawViewManager.instance.pointAmountLabel.text = UserData.Instance.userModel.winPoint.ToString();

        if (result.responseResult.completeIdList.Count != 0)
        {
            foreach (int id in result.responseResult.completeIdList)
            {
                ToastManager.Instance.ShowAchievementCompleteToast(id, true);
            }
        }

        Invoke("GetQuestInfo", 0.5f);

        Popup_Store_SlotSpin2 popup = PopupManager.PushPopup(PopupKind.Popup_Store_SLotSpin) as Popup_Store_SlotSpin2;
        popup.SetPopupInfos(charInfo.charID, result.data.member.traits[3], result.data.member.traits[4]);
    }
}
